﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElCharro01.Models;
using System.Configuration;
using System.Net;
using System.Text;
using System.IO;
using System.Data;

namespace ElCharro01.Areas.User.Controllers
{
    public class PaypalController : Controller
    {
        private Entities db = new Entities();

        public ActionResult PaypalCheckout(int orderId)
        {
            return View(db.OrderSet.Single(o => o.Id == orderId));
        }

        public ActionResult PDT()
        {
            string transactionID = Request.QueryString["tx"];
            string sAmountPaid = Request.QueryString["amt"];

            int orderID = int.Parse(Request.QueryString["cm"]);

            Dictionary<string, string> formVals = new Dictionary<string, string>();
            formVals.Add("cmd", "_notify-synch");
            formVals.Add("at", ConfigurationManager.AppSettings["PayPalPDTToken"]);
            formVals.Add("tx", transactionID);

            string response = GetPayPalResponse(formVals, false);

            if (response.StartsWith("SUCCESS"))
            {
                Decimal amountPaid = 0;
                Decimal.TryParse(sAmountPaid, out amountPaid);

                Order order = db.OrderSet.Single(o => o.Id == orderID);

                if (AmountPaidIsValid(order, amountPaid))
                {
                    //cambio lo stato del pagamento relativo all'ordine
                    order.ConfermaPagamento = true;
                    db.ObjectStateManager.ChangeObjectState(order, EntityState.Unchanged);
                    db.OrderSet.Attach(order);
                    db.ObjectStateManager.ChangeObjectState(order, EntityState.Modified);
                    db.SaveChanges();


                    return RedirectToAction("PayPalComplete", "Order", new { id = order.Id });
                }
                else
                {
                    //Payment amount is off
                    //this can happen if you have a Gift cert at PayPal
                    //be careful of this!
                    //HandleProcessingError(order, new InvalidOperationException("Amount paid (" + amountPaid.ToString("C") + ") was below the order total"));
                    ViewBag.Message = "Ci sono stati problemi con il tuo pagamento Paypal.";
                    return View();
                }
            }
            else
            {
                ViewBag.Message = "Ci sono stati problemi con il tuo pagamento Paypal.";
                return View();
            }
        }

        string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
        {

            string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
                : "https://www.paypal.com/cgi-bin/webscr";


            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);

            // Set values for the request back
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";

            byte[] param = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);

            StringBuilder sb = new StringBuilder();
            sb.Append(strRequest);

            foreach (string key in formVals.Keys)
            {
                sb.AppendFormat("&{0}={1}", key, formVals[key]);
            }
            strRequest += sb.ToString();
            req.ContentLength = strRequest.Length;

            //for proxy
            //WebProxy proxy = new WebProxy(new Uri("http://urlort#");
            //req.Proxy = proxy;
            //Send the request to PayPal and get the response
            string response = "";
            using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
            {

                streamOut.Write(strRequest);
                streamOut.Close();
                using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
                {
                    response = streamIn.ReadToEnd();
                }
            }

            return response;
        }

        bool AmountPaidIsValid(Order order, decimal amountPaid)
        {

            //pull the order
            bool result = true;

            if (order != null)
            {
                if (order.Totale > amountPaid)
                {
                    //_logger.Warn("Invalid order amount to PDT/IPN: " + order.ID + "; Actual: " + amountPaid.ToString("C") + "; Should be: " + order.Total.ToString("C") + "user IP is " + Request.UserHostAddress);
                    result = false;
                }
            }
            else
            {
                //_logger.Warn("Invalid order ID passed to PDT/IPN; user IP is " + Request.UserHostAddress);
            }
            return result;

        }


    }
}
